package edu.njit.hz278.core.web;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

/**
 * 
 * @author Rivers Zhang
 *
 */
public class PageWriter implements Writer {

	private static final VelocityEngine ve = new VelocityEngine();
	private static String vm_prefix, vm_suffix;

	static void init(String prefix, String suffix, Properties prop) {
		ve.init(prop);
		vm_prefix = prefix;
		vm_suffix = suffix;
	}

	@Override
	public void write(HttpServletRequest req, HttpServletResponse resp,
			Object... args) throws IOException {

		assert args.length == 2;
		assert args[1] instanceof ModelView;

		resp.setContentType("text/html");

		ModelView mv = (ModelView) args[1];

		if (!(args[0] instanceof String))
			return;

		String vmName = (String) args[0];
		
		VelocityContext ctx = new VelocityContext();
		if (mv != null)
			for (Map.Entry<String, Object> entry : mv.entrySet())
				ctx.put(entry.getKey(), entry.getValue());

		Template template = ve.getTemplate(vm_prefix + vmName + vm_suffix);
		template.merge(ctx, resp.getWriter());
	}

}
